package com.net.xpay.web.secutiry;

import com.net.common.model.ResultData;
import com.net.common.util.NetUtil;
import com.net.xpay.common.domain.LoginLog;
import com.net.xpay.common.domain.User;
import com.net.xpay.common.manager.LoginLogManager;
import com.net.xpay.common.manager.UserManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
  on 01/02/2018.
 */
@Slf4j
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private SecurityHelper securityHelper;
    @Autowired
    private UserManager userManager;
    @Autowired
    private LoginLogManager loginLogManager;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        ResultData<String> result = new ResultData<>(request.getParameter("tpl"));
        result.setResultMessage("登陆成功");
        try {
            Operator operator = Operator.getCurrentOperator();
            if (operator != null) {
                User user = userManager.getById(operator.getUserId());
                user.setLastLoginTime(LocalDateTime.now());
                user.setLastLoginClient(operator.getClientFrom());
                user.setLastLoginIp(NetUtil.getRequestRealIp(request));
                Long loginCount = user.getLoginCount() == null ? 0L : user.getLoginCount();
                user.setLoginCount(loginCount + 1L);
                userManager.updateByPrimaryKeyWithVersion(user);

                //登录日志
                LoginLog loginLog = LoginLog.getInstance(user);
                loginLogManager.save(loginLog);
            }
        } catch (Exception e) {
            log.warn("onAuthenticationSuccess error", e);
        }
        securityHelper.sendRestResult(response, result);
    }
}
